import 'dart:io';
import 'dart:isolate';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:excel_utils/pages/cpc_report/bean/china_post_luggage_bean.dart';
import 'package:excel_utils/pages/cpc_report/cpc_luggage/bean/cpc_result_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/fee_item_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/luggeasy_bean.dart';
import 'package:excel_utils/pages/cpc_report/bean/waybill_managent_bean.dart';
import 'package:excel_utils/pages/cpc_report/cpc_luggage/isloate/cpc_report_isloate.dart';

part 'cpc_report_event.dart';
part 'cpc_report_state.dart';

class CpcReportBloc extends Bloc<CpcReportEvent, CpcReportState> {
  CpcReportBloc() : super(CpcReportInitial()) {
    on<CpcReportEvent>((event, emit) {

    });

    on<CpcWaybillManagementEvent>((event, emit) async {
      File? waybillManagementFile = event.file;
      String? waybillManagementName = event.sheetName;
      ReceivePort receivePort = ReceivePort();
      final args = {
        "file": waybillManagementFile,
        "sheetName": waybillManagementName,
        "sendPort": receivePort.sendPort,
      };
      Isolate.spawn(waybillManagementExtraction, args);
      await for (var data in receivePort) {
        if (data["code"] == 0) {
          List<WaybillManagementBean> rowData = data["data"];
          emit(CpcWaybillManagementState(waybillManagementList: rowData, message: "运单管理数据提取成功"));
        } else if (data["code"] == 1) {
          double progress = data["progress"];
          emit(CpcWaybillManagementLoadingState(progress: progress));
        } else {}
      }
    });

    on<CpcChinaPostLuggageEvent>((event, emit) async {
      File? file = event.file;
      String? sheetName = event.sheetName;
      ReceivePort receivePort = ReceivePort();
      final args = {
        "file": file,
        "sheetName": sheetName,
        "sendPort": receivePort.sendPort,
      };
      Isolate.spawn(chinaPostLuggageExtraction, args);
      await for (var data in receivePort) {
        if (data["code"] == 0) {
          List<ChinaPostLuggageBean> rowData = data["data"];
          emit(CpcChinaPostLuggageState(chinaPostLuggageList: rowData, message: "中邮数据提取成功"));
        } else  if (data["code"] == 1) {
          double progress = data["progress"];
          emit(CpcChinaPostLuggageLoadingState(progress: progress));
        } else {}
      }
    });

    on<CpcFeeitemlistEvent>((event, emit) async {
      File? file = event.file;
      String? sheetName = event.sheetName;
      ReceivePort receivePort = ReceivePort();
      final args = {
        "file": file,
        "sheetName": sheetName,
        "sendPort": receivePort.sendPort,
      };
      Isolate.spawn(feeitemlistExtraction, args);
      await for (var data in receivePort) {
        if (data["code"] == 0) {
          List<FeeItemBean> rowData = data["data"];
          emit(CpcFeeItemState(feeItemList: rowData, message: "中邮数据提取成功"));
        }  else  if (data["code"] == 1) {
          double progress = data["progress"];
          emit(CpcFeeItemLoadingState(progress: progress));
        } else {}
      }
    });

    //luggeasyExtraction
    on<CpcLuggeasyEvent>((event, emit) async {
      File? file = event.file;
      String? sheetName = event.sheetName;
      ReceivePort receivePort = ReceivePort();
      final args = {
        "file": file,
        "sheetName": sheetName,
        "sendPort": receivePort.sendPort,
      };
      Isolate.spawn(luggeasyExtraction, args);
      await for (var data in receivePort) {
        if (data["code"] == 0) {
          List<LuggeasyBean> rowData = data["data"];
          emit(CpcLuggeasyState(luggeasyList: rowData, message: "中邮数据提取成功"));
        } else if (data["code"] == 1) {
          double progress = data["progress"];
          emit(CpcLuggeasyLoadingState(progress: progress));
        } else {


        }
      }
    });

    on<CppDataMergeEvent>((event, emit) {
      List<WaybillManagementBean> waybillManagementList = event.waybillManagementList; //基准
      List<ChinaPostLuggageBean> chinaPostLuggageList = event.chinaPostLuggageList;
      List<FeeItemBean> feeItemList = event.feeItemList;
      List<LuggeasyBean> luggeasyList = event.luggeasyList;

      List<CpcResultBean> blocList = [];
      for (var waybillManagement in waybillManagementList) {
        String uniqueNo = waybillManagement.waybillNumber.toString();

        CpcResultBean cpcResultBean = CpcResultBean();
        cpcResultBean.a = ""; // a 空白
        cpcResultBean.e = "";
        cpcResultBean.h = "";
        cpcResultBean.k = "";
        cpcResultBean.n = "";
        cpcResultBean.o = "";
        cpcResultBean.p = "";
        cpcResultBean.q = "";
        cpcResultBean.s = "";
        cpcResultBean.t = "";
        cpcResultBean.u = "";
        cpcResultBean.v = "";
        cpcResultBean.x = "";
        cpcResultBean.y = "";
        cpcResultBean.z = "";
        cpcResultBean.aa = "";
        cpcResultBean.ab = "";

        cpcResultBean.b = waybillManagement.accountName;
        cpcResultBean.c = waybillManagement.entryDate;
        cpcResultBean.f = waybillManagement.orderAddress;
        cpcResultBean.w = waybillManagement.waybillNumber;

        LuggeasyBean? luggeasyBean = luggeasyList.singleWhere((element){
          return element.cpOrderNo == uniqueNo;
        },orElse: (){
          return LuggeasyBean(date: "", cpOrderNo: "", kg: "", priceHKD: "", declarationPriceHKD: "");
        });
        cpcResultBean.d = luggeasyBean.date??"";
        cpcResultBean.i = luggeasyBean.kg;
        cpcResultBean.l = luggeasyBean.priceHKD;
        cpcResultBean.r = luggeasyBean.declarationPriceHKD;

        FeeItemBean feeItemBean = feeItemList.singleWhere((element) => element.trackingNumber == uniqueNo,
        orElse: () => FeeItemBean(trackingNumber: "", kg: "", price: "")
        );
        cpcResultBean.j = feeItemBean.kg;
        cpcResultBean.m = feeItemBean.price;

        ChinaPostLuggageBean chinaPostLuggageBean = chinaPostLuggageList.singleWhere((element) => element.trackingNo == uniqueNo,
        orElse: () => ChinaPostLuggageBean(trackingNo: "", localCurrentAction: ""));
        cpcResultBean.g = chinaPostLuggageBean.localCurrentAction;

        blocList.add(cpcResultBean);
      }
      emit(CpcDataMergeSuccessState(cpcResultList: blocList, message: "数据合并成功"));

    });

    on<CpcWriteFileEvent>((event, emit) async {

      emit(CpcWriteFileLoadingState(progress: 0));
      List<CpcResultBean> cpcResultList = event.cpcResultList;
      File writeFile = event.writeFile;
      String writeName = event.writeName;

      ReceivePort receivePort = ReceivePort();
      final args = {
        "cpcResultList": cpcResultList,
        "writeFile": writeFile,
        "sheetName": "012025",
        "sendPort": receivePort.sendPort,
      };
      Isolate.spawn(writeDataToExcel, args);
      await for (var data in receivePort) {
        if (data["code"] == 0) {

          emit(CpcWriteFileSuccessState());
        } else if (data["code"] == 2) {

          emit(CpcWriteFileLoadingState(progress: data["progress"] ?? 0.0));
        } else {
          emit(CpcWriteFileFailureState(failureMessage: "数据写入失败"));
        }
      }

    });

  }
}
